package com.bayihouse.excel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.bayihouse.common.ErrorCode;
import com.bayihouse.exception.BusinessException;

public class NumberConverter implements Converter<Integer> {

    @Override
    public Class supportJavaTypeKey() {
        return Integer.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }



    @Override
    public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                     GlobalConfiguration globalConfiguration) {
        String value = cellData.getStringValue();
        int len = value.length();
        String numStr = "";
        for (int i = 0; i < len; i++) {
            if (value.charAt(i) >= '0' && value.charAt(i) <= '9') {
                while (i < len && value.charAt(i) >= '0' && value.charAt(i) <= '9') {
                    numStr += value.charAt(i++);
                }
                break;
            }
        }
        if (numStr.length() > 0) {
            return Integer.parseInt(numStr);
        }
        throw new BusinessException(ErrorCode.OPERATION_ERROR, String.format("excel中%s数字转换失败", contentProperty.getField().getName()));
    }
}
